#include "StdAfx.h"
#include "DirModel.h"


namespace DuiLib
{
	CDirModel::CDirModel(const CDuiString& root, const CDuiString& filter)
		:CCommonTreeModel(0, 5)
	{
		m_RootPath = root;
		m_Filter = filter;

		ParseDir(CModelIndex());
	}
	CDirModel::~CDirModel()
	{
	}

	void CDirModel::ParseDir(const CModelIndex& parent)
	{
		CDuiString path;

		if (parent==CModelIndex())
		{
			path = m_RootPath;
		}
		else
		{
			CModelIndex&& parentPathIndex = index(parent.row(), 4, parent.parent());
			path = parentPathIndex.data().WideStrVal();
		}

		int rows = rowCount(parent);
		removeRows(0, rows, parent);

		FileInfoVector&& fileInfos = getFilesInDir(path, m_Filter);
		int fileCount = fileInfos.size();
		if (fileCount <= 0)
		{
			return;
		}

		insertRows(0, fileInfos.size(), parent);

		rows = rowCount(parent);
		for (int i = 0; i < rows; i++)
		{
			if (i>=(int)fileInfos.size())
			{
				break;
			}

			CDuiString fileName = fileInfos[i].name;
			CDuiString filePath = path + _T("/") + fileName;

			UInt fileSize = fileInfos[i].size;
			UInt fileType = fileInfos[i].type;

			CModelIndex childIndex = index(i, 0, parent);
			setData(childIndex, CVar(fileName.GetData()));

			childIndex = index(i, 1, parent);
			setData(childIndex, CVar(0));

			childIndex = index(i, 2, parent);
			setData(childIndex, CVar((int)fileType));

			childIndex = index(i, 3, parent);
			setData(childIndex, CVar((int)fileSize));

			childIndex = index(i, 4, parent);
			setData(childIndex, CVar(filePath.GetData()));
		}
	}

	//CModelIndex CDirModel::index(const CDuiString& path, int column = 0)
	//{
	//}

	bool CDirModel::findDir(const CDuiString& path)
	{
		return true;
	}

	CDuiString CDirModel::filePath(const CModelIndex& index)
	{
		return CDuiString();
	}

	CDuiString CDirModel::fileName(const CModelIndex& index)
	{
		return CDuiString();
	}


	FileInfoVector CDirModel::getFilesInDir(const CDuiString& path, const CDuiString& filter)
	{
		FileInfoVector fileInfoList;
		
		CDuiString filePath = path + _T("/") + filter;

		WIN32_FIND_DATA findFileData;
		HANDLE hFind = FindFirstFile(filePath.GetData(), &findFileData);
		if (INVALID_HANDLE_VALUE == hFind)
		{
			return fileInfoList;
		}

		do
		{
			CDuiString fileName = findFileData.cFileName;
			UInt fileAttr = findFileData.dwFileAttributes;
			UInt fileSize = findFileData.nFileSizeLow;
			if (fileName==_T(".") || fileName==_T(".."))
			{
				continue;
			}

			if (fileAttr & FILE_ATTRIBUTE_DIRECTORY)
			{
				fileInfoList.emplace_back(fileName, fileSize, FileType_Dir);
			}
			else
			{
				fileInfoList.emplace_back(fileName, fileSize, FileType_File);
			}
		} while (FindNextFile(hFind, &findFileData));

		FindClose(hFind);

		return fileInfoList;
	}

}